package com.andaily.service.impl;

import com.andaily.domain.dto.user.UserDto;
import com.andaily.domain.dto.user.UserFormDto;
import com.andaily.domain.shared.security.AndailyUserDetails;
import com.andaily.domain.user.User;
import com.andaily.domain.user.UserRepository;
import com.andaily.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Shengzhao Li
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Not found any user for username[" + username + "]");
        }
        return new AndailyUserDetails(user);
    }

    @Override
    public UserDto loadUserDto(String guid) {
        if (guid == null) {
            return null;
        }
        final User user = userRepository.findByGuid(guid, User.class);
        return user == null ? null : new UserDto(user);
    }

    @Override
    public String persistUserFormDto(UserFormDto userFormDto) {
        User user = userFormDto.toDomain();
        userRepository.saveOrUpdate(user);
        return user.guid();
    }
}